package com.atguigu.tms.mock.task;


import com.atguigu.mock.util.LineInfo;
import com.atguigu.mock.util.MyDateUtil;
import com.atguigu.mock.util.RandomBox;
import com.atguigu.mock.util.RandomNum;
import com.atguigu.tms.mock.bean.*;
import com.atguigu.tms.mock.config.AppConfig;
import com.atguigu.tms.mock.constant.TmsConstant;
import com.atguigu.tms.mock.service.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.atguigu.tms.mock.constant.TmsConstant.TASK_TYPE_COLLECT;


@Component
@Slf4j
public class ExpressCollectMockTask {



    @Autowired
    BaseComplexService baseComplexService;

    @Autowired
    OrderInfoService orderInfoService;


    @Autowired
    EmployeeInfoService employeeInfoService;

    @Autowired
    ExpressCourierService expressCourierService;

    @Autowired
    ExpressCourierComplexService expressCourierComplexService;


    @Autowired
    ExpressTaskCollectService expressTaskCollectService;

    @Autowired
    OrderOrgBoundService orderOrgBoundService;

    @Autowired
    LineBaseInfoService lineBaseInfoService;

    @Autowired
    TransportPlanLineDetailService transportPlanLineDetailService;

    @Autowired
    OrderTraceLogService orderTraceLogService;


    @Autowired
    ExpressTaskDeliveryService expressTaskDeliveryService;

 // @Scheduled(cron = "0/15 * * * * ?")
  public  void executeTask(){
     log.info("检查快递任务....");
    //  List<OrderInfo> orderInfoPaidList = getOrderInfoPaidList();



  }


  public void mainBatchTask(){


      expressCourierService.loadCache();


      for (int i = 0; i < AppConfig.collect_hours.length; i++) {
          String collectHour = AppConfig.collect_hours[0];
          String commitHour = AppConfig.commit_hours[0];
          log.info("--- 揽货快递 开始 ，时间："+collectHour+"   ---");
         // doCollectCommit(   collectHour,  commitHour );
          log.info("--- 揽货快递 完成 ，时间："+commitHour+"   ---");
      }


  }


  public void doCollect(Date curDate,Integer collectStartHour ,Integer collectCurHour){
      String collectStartDateStr=AppConfig.mock_date_str+" "+ StringUtils.leftPad(collectStartHour+"", 2,"0") +":00:00";


      List<ExpressTaskCollect> expressTaskCollectList = getExpressTaskCollectList(collectStartDateStr);
      log.warn("------- 待收快递  任务："+expressTaskCollectList.size()+" 个  ---");
      Map<Long, ExpressCourier> courierWithTaskMap = getCourierWithTask(expressTaskCollectList);
      for (ExpressCourier expressCourier : courierWithTaskMap.values()) {
          courierDoCollect(expressCourier, curDate  );  //揽货
      }
  }


  //所有的快递员做一次接收交货
  public   void   doCommit(  Integer commitCurHour ){
        //检查已揽收未提交的任务
      String commitCurHourDateStr=AppConfig.mock_date_str+" "+ StringUtils.leftPad(commitCurHour+"", 2,"0") +":00:00";
      Date commitDate = MyDateUtil.initDate(AppConfig.mock_date_str, commitCurHour, 0);
      List<ExpressTaskCollect> expressTaskCommitList = getExpressTaskCommitList(commitCurHourDateStr);
      for (ExpressTaskCollect expressTaskCollect : expressTaskCommitList) {
          courierDoCommit(  expressTaskCollect,  commitDate );
      }


  }


  //某个快递员去收快递
  private  void  courierDoCollect(ExpressCourier expressCourier,Date collectHourDatetime  )  {

      List<ExpressTaskCollect> expressTaskCollectList = expressCourier.getExpressTaskCollectList();


      //从任务中取出一件 ，尝试完成
      RandomBox ifCanFinishBox = new RandomBox(85, 15);

      if(ifCanFinishBox.getRandBoolValue() ) {
          ExpressTaskCollect expressTaskCollect = expressTaskCollectList.get(0);
          expressTaskCollect.setActualCollectedTime(collectHourDatetime);
          expressTaskCollect.setUpdateTime(collectHourDatetime);
          expressTaskCollect.setStatus(TmsConstant.COLLECT_STATUS_COLLECTED);
          expressTaskCollectService.saveOrUpdate(expressTaskCollect,true);



          OrderInfo orderInfo = orderInfoService.getById(expressTaskCollect.getOrderId(), true);
          orderInfo.setStatus(TmsConstant.ORDER_STATUS_COLLECTED);
          orderInfo.setUpdateTime(collectHourDatetime);
          orderInfoService.saveOrUpdate(orderInfo,true);


          genOrderTraceLogCollect(  orderInfo,  expressTaskCollect);
      }


  }


    private  void  courierDoCommit(ExpressTaskCollect expressTaskCollect,Date commitHourDatetime )  {

            //交货
            expressTaskCollect.setActualCommitTime(commitHourDatetime);
            expressTaskCollect.setUpdateTime(commitHourDatetime);
            expressTaskCollect.setStatus(TmsConstant.COLLECT_STATUS_COMMITTED);
            expressTaskCollectService.saveOrUpdate(expressTaskCollect,true);

            ExpressCourier expressCourier = expressCourierService.getById(expressTaskCollect.getCourierEmpId(),true);

            //入站
            OrderOrgBound orderOrgBound=new OrderOrgBound();
            orderOrgBound.setOrgId(expressCourier.getOrgId());
            orderOrgBound.setOrderId(expressTaskCollect.getOrderId());
            orderOrgBound.setInboundEmpId(expressCourier.getEmpId());
            orderOrgBound.setInboundTime(commitHourDatetime);
            orderOrgBound.setStatus(TmsConstant.BOUND_STATUS_IN);
            orderOrgBound.setCreateTime(commitHourDatetime);
            orderOrgBoundService.saveOrUpdate(orderOrgBound,true);

            //改订单状态 待转运
            OrderInfo orderInfo = orderInfoService.getById(expressTaskCollect.getOrderId(), true);
            orderInfo.setStatus(TmsConstant.ORDER_STATUS_PENDING);
            orderInfo.setUpdateTime(commitHourDatetime);
            orderInfoService.saveOrUpdate(orderInfo,true);

            //增加日志
            genOrderTraceLogCommit(orderInfo,expressTaskCollect);



            if(!orderInfo.getSenderDistrictId().equals(orderInfo.getReceiverDistrictId()) ) {
                //生成路线规划
                List<LineInfo> lineInfoList = lineBaseInfoService.calcLineInfo(orderInfo.getSenderDistrictId() , orderInfo.getReceiverDistrictId()  );
                List<TransportPlanLineDetail> transportPlanLineDetailList = new ArrayList<>();
                for (LineInfo lineInfo : lineInfoList) {
                    TransportPlanLineDetail transportPlanLineDetail = new TransportPlanLineDetail();
                    transportPlanLineDetail.setOrderId(orderInfo.getId());
                    transportPlanLineDetail.setStartOrgId(Long.parseLong(lineInfo.getFrom()));
                    transportPlanLineDetail.setEndOrgId(Long.parseLong(lineInfo.getTo()));
                    transportPlanLineDetail.setLineBaseId(lineInfo.getId());
                    transportPlanLineDetail.setCreateTime(orderInfo.getUpdateTime());
                    transportPlanLineDetail.setIsDeleted("0");

                    transportPlanLineDetailList.add(transportPlanLineDetail);
                }
                transportPlanLineDetailService.saveOrUpdateBatch(transportPlanLineDetailList,1000,true);
            }else{
                //如果时同一区域的快递 直接生成派送任务
                orderOrgBound.setStatus(TmsConstant.BOUND_STATUS_DELIVERY_TASKED);
                orderOrgBound.setUpdateTime(commitHourDatetime);
                orderOrgBoundService.saveOrUpdate(orderOrgBound,true);

                 expressTaskDeliveryService.genExpressTaskDelivery(commitHourDatetime, orderOrgBound);

            }



    }


    //查询所有待处理的货物
  private List<ExpressTaskCollect> getExpressTaskCollectList(String collectDateStr){

      QueryWrapper<ExpressTaskCollect> queryWrapper = new QueryWrapper<ExpressTaskCollect>().eq("status", TmsConstant.COLLECT_STATUS_ASSIGNED)
              .orderByAsc("create_time");

      List<ExpressTaskCollect> expressTaskCollectList = expressTaskCollectService.list(queryWrapper);
      return expressTaskCollectList;

  }

    //查询所有待处理的货物
    private List<ExpressTaskCollect> getExpressTaskCommitList(String commitDateStr){

        QueryWrapper<ExpressTaskCollect> queryWrapper = new QueryWrapper<ExpressTaskCollect>()
                .eq("status", TmsConstant.COLLECT_STATUS_COLLECTED);
        List<ExpressTaskCollect> expressTaskCollectList = expressTaskCollectService.list(queryWrapper);
        return expressTaskCollectList;

    }


  //把待收货的任务 分配给快递员
  private  Map<Long , ExpressCourier> getCourierWithTask(List<ExpressTaskCollect> expressTaskCollectList){
      Map<Long , ExpressCourier>  courierWithTaskMap=new HashMap<>(expressTaskCollectList.size());

      for (ExpressTaskCollect expressTaskCollect : expressTaskCollectList) {
          Long courierEmpId = expressTaskCollect.getCourierEmpId();
          ExpressCourier expressCourier = courierWithTaskMap.get(courierEmpId);
          if(expressCourier ==null){
                courierEmpId  = expressTaskCollect.getCourierEmpId();
                expressCourier = expressCourierService.getById(courierEmpId, true);
                expressCourier.getExpressTaskCollectList().clear();
          }
          expressCourier.getExpressTaskCollectList().add(expressTaskCollect);
          courierWithTaskMap.put(courierEmpId,expressCourier);
      }

      return courierWithTaskMap;

  }


    public void genOrderTraceLogCollect(OrderInfo orderInfo,ExpressTaskCollect expressTaskCollect){
        OrderTraceLog orderTraceLog = new OrderTraceLog();
        orderTraceLog.setOrderId(orderInfo.getId());
        orderTraceLog.setTraceDesc("已取件");
        orderTraceLog.setCreateTime(expressTaskCollect.getUpdateTime());
        orderTraceLog.setCurTaskId(expressTaskCollect.getId());
        orderTraceLog.setChargeEmpId(expressTaskCollect.getCourierEmpId());
        orderTraceLog.setTaskType(TASK_TYPE_COLLECT);
        orderTraceLog.setIsDeleted("0");
        orderTraceLogService.saveOrUpdate(orderTraceLog );
    }


    public void genOrderTraceLogCommit(OrderInfo orderInfo,ExpressTaskCollect expressTaskCollect){
        OrderTraceLog orderTraceLog = new OrderTraceLog();
        orderTraceLog.setOrderId(orderInfo.getId());

        orderTraceLog.setTraceDesc("已收入 "+expressTaskCollect.getOrgName()+"待转运");
        orderTraceLog.setCreateTime(expressTaskCollect.getUpdateTime());
        orderTraceLog.setCurTaskId(expressTaskCollect.getId());
        orderTraceLog.setChargeEmpId(expressTaskCollect.getCourierEmpId());
        orderTraceLog.setTaskType(TASK_TYPE_COLLECT);
        orderTraceLog.setIsDeleted("0");
        orderTraceLogService.saveOrUpdate(orderTraceLog );
    }


}
